package com.tarena.lbs.business.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.constant.BusinessTypes;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.BusinessLoginParam;
import com.tarena.lbs.business.pojo.param.BusinessParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.service.BusinessService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    private BusinessRepository businessRepository;

    @Autowired
    private StoreRepository storeRepository;



    @DubboReference
    private AttachApi attachApi;

    @Override
    public BusinessVO login(BusinessLoginParam param) {
        log.debug("开始执行商家登录逻辑，请求参数: {}", param);

        // 参数校验
        if (param == null || param.getBusinessName() == null || param.getBusinessName().isEmpty()) {
            throw new RuntimeException("商家名称不能为空");
        }

        BusinessPO po = businessRepository.findByName(param.getBusinessName());
        if (po == null) {
            log.debug("商家不存在，名称: {}", param.getBusinessName());
            throw new RuntimeException("商家不存在");
        }

        BusinessVO vo = new BusinessVO();
        BeanUtils.copyProperties(vo, po); // 注意顺序：目标在前

        log.info("登录成功，商家ID: {}", vo.getId());
        return vo;
    }


    @Override
    public PageResult<BusinessVO> pageList(BusinessQuery query) throws BusinessException {
        log.debug("开始查询商家列表，参数: {}", query);
        PageInfo<BusinessPO> pageInfo = businessRepository.pageList(query);
        List<BusinessPO> poList = pageInfo.getList();
        // 将 BusinessPO 转换为 BusinessVO
        List<BusinessVO> voList = CollectionUtils.isNotEmpty(poList)
                ? poList.stream()
                .map(po -> {
                    BusinessVO vo = new BusinessVO();
                    BeanUtils.copyProperties(vo, po); // 注意属性拷贝顺序
                    return vo;
                })
                .collect(Collectors.toList())
                : new ArrayList<>();

        // 构建返回值
        PageResult<BusinessVO> result = new PageResult<>();
        result.setPageSize(pageInfo.getPageSize());
        result.setTotal(pageInfo.getTotal());

        return result;
    }


    @Override
    public void save(BusinessParam param) throws BusinessException {
        log.debug("新增商家请求，参数={}", param);
//
//        // 权限校验
//        UserPrinciple user = AuthenticationContextUtils.get();
//        Asserts.isTrue(user == null, new BusinessException("USER_NOT_LOGIN", "用户未登录"));



        // 校验商家名称是否重复
        String businessName = param.getBusinessName();
        Long count = businessRepository.countByBusinessName(businessName);
        Asserts.isTrue(count > 0, new BusinessException("BUSINESS_NAME_EXISTS", "商家名称已存在"));

        // 构建实体对象
        BusinessPO businessPO = new BusinessPO();
        BeanUtils.copyProperties(businessPO, param);
        businessPO.setEntryTime(new Date());

        // 插入数据
        businessRepository.insert(businessPO);

        // 绑定图片
        Integer businessId = businessPO.getId();
        bindPictures(businessId, param);
    }


    @Override
    public void delete(Integer businessId) throws BusinessException {
        log.debug("删除商家请求，ID={}", businessId);
        // 软删或硬删
        businessRepository.deleteById(businessId);
    }

    @Override
    public BusinessStoreVO busiStoreDetail(Integer businessId) throws BusinessException {
        log.debug("查询商家详情，ID={}", businessId);

        // 查询商家信息
        BusinessPO businessPO = businessRepository.busiStoreDetail(businessId);
        BusinessStoreVO businessStoreVO = new BusinessStoreVO();
        if (businessPO != null) {
            BeanUtils.copyProperties(businessStoreVO, businessPO);
        }

        // 查询店铺信息
        List<StorePO> storePOS = storeRepository.selectStoreById(businessId);
        List<StoreVO> storeVOS = CollectionUtils.isNotEmpty(storePOS)
                ? storePOS.stream()
                .map(po -> {
                    StoreVO vo = new StoreVO();
                    BeanUtils.copyProperties(vo, po);
                    return vo;
                })
                .collect(Collectors.toList())
                : new ArrayList<>();

        businessStoreVO.setStoreVOList(storeVOS);
        return businessStoreVO;
    }

    private void bindPictures(Integer businessId, BusinessParam param) throws BusinessException {
        List<PicUpdateParam> picUpdateParams = new ArrayList<>();

        if (param.getBusinessLicense() != null && !param.getBusinessLicense().isEmpty()) {
            PicUpdateParam licenseParam = new PicUpdateParam();
            licenseParam.setBusinessType(BusinessTypes.BIZ_LICENSE);
            licenseParam.setBusinessId(businessId);
            licenseParam.setFileUuid(getUuid(param.getBusinessLicense()));
            picUpdateParams.add(licenseParam);
        }

        if (param.getBusinessLogo() != null && !param.getBusinessLogo().isEmpty()) {
            PicUpdateParam logoParam = new PicUpdateParam();
            logoParam.setBusinessType(BusinessTypes.BIZ_LOGO);
            logoParam.setBusinessId(businessId);
            logoParam.setFileUuid(getUuid(param.getBusinessLogo()));
            picUpdateParams.add(logoParam);
        }

        if (!picUpdateParams.isEmpty()) {
            Boolean result = attachApi.batchUpdateBusiness(picUpdateParams);
            Asserts.isTrue(!result, new BusinessException("BINDING_FAILURE", "图片绑定失败"));
        }
    }

    private String getUuid(String url) throws BusinessException {
        String[] parts = url.split("/");
        Asserts.isTrue(parts.length < 5, new BusinessException("INVALID_URL_FORMAT", "URL格式不正确"));
        return parts[4];
    }
}
